package com.controller;

import com.pojo.book;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

public class deleteServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        HttpSession session = req.getSession();
        String bookid = req.getParameter("bookid");
        String p = req.getParameter("page");
        int page = Integer.parseInt(p);
        PrintWriter out = resp.getWriter();
        if(bookid==null||bookid.equals("")){
            out.print("没有传入图书编号。。。");
            return;
        }else {
            Map<String, List<book>> buycar = (Map<String, List<book>>) session.getAttribute("car");
         String uid=null;
            Cookie[] cookies = req.getCookies();
            for (int i = 0; i < cookies.length; i++) {
                if(cookies[i].getName().equals("loginUser")){
                    uid=   cookies[i].getValue();
                    break;
                }
            }
           if(uid==null||uid.equals("")){
               out.print("未登录！！！");
               return;
           }else {
               List<book> books = buycar.get(uid);
               for (int i = 0; i < books.size(); i++) {
                   if(books.get(i).getBookid().equals(bookid)){
                       books.remove(i);
                       break;
                   }
               }

               //进行简单判断一下page来自哪里，防止修改参数
               switch (page){

                   case 1:
                       //这里不能用重定向，不然会clear掉reques请求域中的数据
                       req.getRequestDispatcher("/buy.jsp").forward(req,resp);
                       break;

                   case 2 :
                       resp.sendRedirect("showServlet");
                       break;
                       //防止页面参数被修改导致错误
                   default:
                    req.getRequestDispatcher("/index.jsp").forward(req,resp);
                       break;

               }


           }





            }
        }








    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
